﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using log4net;

namespace MND.Users
{
    class UserManager
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(UserManager));

        private List<User> Users = new List<User>();

        public User[] CurrentUsers
        {
            get
            {
                User[] users;
                lock (Users)
                {
                    users = Users.ToArray();
                }
                return users;
            }
        }

        private UserCommandProcessor processor;


        public UserManager(Telnet.IMessageSourceOrigin pOrigin)
        {
            pOrigin.NewConnection += new EventHandler<Telnet.NewConnectionEventArgs>(pOrigin_NewConnection);
            processor = new UserCommandProcessor(this);
        }

        void pOrigin_NewConnection(object sender, Telnet.NewConnectionEventArgs e)
        {
            lock (Users)
            {
                User u = new User(e.Connection, this);
                u.LoggedOut += new EventHandler<EventArgs>(u_LoggedOut);
                Users.Add(u);
            }
        }

        void u_LoggedOut(object sender, EventArgs e)
        {
            lock (Users)
            {
                Users.Remove((User)sender);
            }
        }

        public void Tick()
        {
            lock (Users)
            {
                foreach (User u in Users)
                {
                    u.Tick();
                }
            }
        }

        public void EnqueueCommand(Commands.UserCommand uc)
        {
            lock (processor)
            {
                if (uc != null)
                {
                    processor.Enqueue(uc);
                }
            }
        }
    }
}
